<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>动态组件</title>
    <script src="js/vue.js"></script>
</head>

<body>
    <div id="app">
        <button @click="btnCustom(1)">切换到组件1</button>
        <button @click="btnCustom(2)">切换到组件2</button>
        <button @click="btnCustom(3)">切换到组件3</button>

        <keep-alive>
            <component :is="current"></component>
        </keep-alive>
    </div>
    <script>
        var custom1 = Vue.component('custom1', {
            template: `
                <div @click="ChangeDivBg">我是自定义组件1</div>
            `,
            methods: {
                ChangeDivBg(ev) {
                    // console.log(ev.target);
                    ev.target.style.backgroundColor = 'red'
                }
            }
        });
        var custom2 = Vue.component('custom2', {
            template: `
                <div>我是自定义组件2</div>
            `
        });
        var custom3 = Vue.component('custom3', {
            template: `
                <div>我是自定义组件3</div>
            `
        });


        new Vue({
            el: '#app',
            data: {
                current: custom1
            },
            methods: {
                btnCustom(index) {
                    this.current = 'custom' + index
                        // ES6连接字符串的方法
                        // this.current = `custom${index}`
                }
            }
        })
    </script>
</body>

</html>